package com.gz.logistics.app;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.logistics.R;
import com.gz.logistics.adapter.SpinnerAdapter;
import com.gz.logistics.adapter.SumOfMoneyAdapter;
import com.gz.logistics.fragment.HomeFragment;
import com.gz.logistics.fragment.OutingFragment;
import com.gz.logistics.fragment.PersonFragment;
import com.gz.logistics.fragment.QureyOrderFragment;
import com.gz.logistics.library.IAuthor;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.GetStoreHouseListener;
import com.gz.logistics.library.listener.GetSumOfMoneyListener;
import com.gz.logistics.library.pojo.CustomerSpinnerObject;
import com.gz.logistics.library.pojo.Money;
import com.gz.logistics.library.pojo.StoreHouse;
import com.gz.logistics.library.pojo.SumOfMoney;
import com.gz.logistics.library.pojo.UserInfo;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.library.util.CrashHandler;
import com.gz.logistics.library.util.PreferenceModel;
import com.gz.logistics.util.ToastUtils;
import com.gz.logistics.widget.DoubleDatePickerDialog;
import com.gz.logistics.widget.LoadingCover;
import com.gz.logistics.widget.SpinerPopWindow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class AccountActivity extends Activity implements View.OnClickListener,DoubleDatePickerDialog.OnDateSetListener,LoadingCover.OnLoadingCoverRefreshListener {


    private static final String TAG = AccountActivity.class.getSimpleName();

    private UserInfo userInfo;
    private Context mContext;
    private List<CustomerSpinnerObject> storehouse;//仓库列表
    private SpinnerAdapter mStoreHouseSpinnerAdapter;
    private SpinerPopWindow mStoreHousePopwindow;
    private myGetStoreListener myGetStoreListener;
    private MyPartSpinnerOnItemSelectListener mPartSpinnerListener;
    private RelativeLayout rl_choice_for_part;//仓库下拉框
    private RelativeLayout rl_choice_for_time;//时间选择
    private int storehouseid;//仓库id
    private DoubleDatePickerDialog timeDialog;
    private Calendar mCalendar;
    private String startTime = null; //开始时间
    private String endTime = null;//结束时间
    private MyHandler mHandler;
    private TextView sumofrealmoney;//实收金额
    private TextView sumofmoney;//应收金额
    private Dialog mLoadingData;
    private SumOfMoneyAdapter sumOfMoneyAdapter;
    private SumOfMoney sumOfMoneyList;//汇总金额
    private List<Money> money;
    private LoadingCover mloadCover;
    private PullToRefreshListView mPullList;
    private BuildingListener buildingListener;
    private Date date;
    private ImageView img_title;
    private RelativeLayout back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_home);
        init();
        initListener();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.release();
        myGetStoreListener.release();
        mPartSpinnerListener.release();

    }

    /**
     * 各种界面控件的点击事件
     * @param view
     */
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_choice_for_part:
                if (storehouse.size() <= 0){
                    ToastUtils.showToast(this,"仓库列表为空");
                }
                mStoreHousePopwindow.setWidth(rl_choice_for_part.getWidth());
                mStoreHousePopwindow.setHeight(350);
                mStoreHousePopwindow.showAsDropDown(rl_choice_for_part);
                break;
            case R.id.rl_choice_for_time:
                timeDialog.show();
                break;
            case R.id.back:
                finish();
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Define.ACTIVITY_CODE_ORDER_DETAIL && resultCode == Define.ACTIVITY_CODE_ORDER_DETAI_CHANGE){
            if (data != null){

            }
        }

    }



    /**
     *     初始化控件
     */
    private void init() {
        mContext = getApplicationContext();
        userInfo = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        rl_choice_for_part = (RelativeLayout) findViewById(R.id.rl_choice_for_part);
        rl_choice_for_time = (RelativeLayout) findViewById(R.id.rl_choice_for_time);
        sumofmoney = (TextView) findViewById(R.id.sumofmoney);
        sumofrealmoney = (TextView) findViewById(R.id.sumofrealmoney);
        img_title = (ImageView) findViewById(R.id.img_title);
        img_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoadingData.show();
                loadbuildingData();
            }
        });
        storehouse = new ArrayList<CustomerSpinnerObject>();
        sumOfMoneyList = new SumOfMoney();
        money = new ArrayList<Money>();
        mHandler = new MyHandler(this);
        buildingListener = new BuildingListener(this);

        sumOfMoneyAdapter = new SumOfMoneyAdapter(money,mContext);//适配器
        mPullList = (PullToRefreshListView) findViewById(R.id.list);
        mPullList.setAdapter(sumOfMoneyAdapter);
        mPullList.setMode(PullToRefreshBase.Mode.DISABLED);

        mloadCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
        mloadCover.setOnLoadingCoverRefreshListener(this);

        mLoadingData = new Dialog(this,R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);

        mStoreHouseSpinnerAdapter = new SpinnerAdapter(this.getApplicationContext(),storehouse);
        mStoreHousePopwindow = new SpinerPopWindow(this);
        mStoreHousePopwindow.setAdatper(mStoreHouseSpinnerAdapter);
        mHandler.sendEmptyMessage(1);
        mCalendar = Calendar.getInstance();
        timeDialog = new DoubleDatePickerDialog(this,0,this,mCalendar.get(Calendar.YEAR),mCalendar.get(Calendar.MONTH),mCalendar.get(Calendar.DATE),true);

        back = (RelativeLayout) findViewById(R.id.back);
        back.setOnClickListener(this);
        date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        endTime = format.format(new Date(date.getTime()));//系统当前的时间
        startTime = format1.format(new Date(date.getTime()))+" 00:00:00";//系统当天的凌晨
        loadbuildingData();

    }

    /**
     * 初始化各种监听器
     */
    private void initListener() {
        myGetStoreListener = new myGetStoreListener(this);
        rl_choice_for_part.setOnClickListener(this);
        rl_choice_for_time.setOnClickListener(this);
        mPartSpinnerListener = new MyPartSpinnerOnItemSelectListener(this);
        mStoreHousePopwindow.setItemListener(mPartSpinnerListener);
    }

    /**
     *  弹出时间选择 Dialog，并选择对应开始和介素时间后，点击确定按钮，将会触发以下方法
     *
     */
    @Override
    public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear, int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear, int endDayOfMonth) {
        startTime = String.format("%d-%d-%d",startYear,startMonthOfYear+1,startDayOfMonth)+" 00:00:00";
        endTime = String.format("%d-%d-%d",endYear,endMonthOfYear+1,endDayOfMonth)+" 23:59:59";
        CrashHandler.i(TAG, "开始时间=" + startTime + "结束时间=" + endTime);
        mLoadingData.show();
        loadbuildingData();
    }

    @Override
    public void onLoadingCoverRefresh() {
        loadbuildingData();
    }

    public static class MyHandler extends android.os.Handler{
        private AccountActivity mOuter;

        public MyHandler(AccountActivity mOuter) {
            this.mOuter = mOuter;
        }
        public void release(){
            new WeakReference<AccountActivity>(mOuter);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    IOrder.getInstance().getStoreHouse(Integer.toString(mOuter.userInfo.getUser_id()),mOuter.myGetStoreListener);
                    break;
            }
        }
    }
    /**
     * 获取仓库的监听器
     * 杜志娟 2016-03-15
     */
    public static  class myGetStoreListener extends GetStoreHouseListener {
        private AccountActivity mOuter;

        public myGetStoreListener(AccountActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<AccountActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess(List<StoreHouse> storeHouses) {
            StoreHouse ignorePart = new StoreHouse();
            ignorePart.setStore_houseid(0);
            ignorePart.setStore_housename("默认");
            ignorePart.setIsSelected(true);
            storeHouses.add(0, ignorePart);

            mOuter.storehouse.clear();
            mOuter.storehouse.addAll(storeHouses);


        }
        @Override
        public void onNoMoreData() {

        }
        @Override
        public void onResponseFailed() {

        }
    }
    /**
     *仓库下拉列表的 item 点击事件监听器
     * 杜志娟 2016-03-14
     */
    public static class MyPartSpinnerOnItemSelectListener implements SpinerPopWindow.ISpinnerOnItemSelectListener {
        private AccountActivity mOuter;

        public MyPartSpinnerOnItemSelectListener(AccountActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<AccountActivity>(mOuter);
        }
        @Override
        public void onSpinnerItemClick(int position) {
            mOuter.mLoadingData.show();
            mOuter.storehouseid = ((StoreHouse)mOuter.storehouse.get(position)).getStore_houseid();//查询小区所需仓库的id

            for(int j = 0 ; j < mOuter.storehouse.size() ; j++){ // 把选中的仓库置为选中状态，
                if(j == position){
                    (mOuter.storehouse.get(j)).setIsSelected(true);
                }else{
                    (mOuter.storehouse.get(j)).setIsSelected(false);
                }
            }
            mOuter.loadbuildingData();
        }
    }
    private void loadbuildingData() {
        IOrder.getInstance().setGetSumOfMoney(String.valueOf(storehouseid),startTime,endTime,buildingListener);
    }

    /**
     * 查询汇总金额
     */
    private static class BuildingListener extends GetSumOfMoneyListener {
        private AccountActivity mOuter;
        public BuildingListener(AccountActivity outer){
            this.mOuter = outer;
        }
        public void release(){
            new WeakReference<AccountActivity>(mOuter);
        }

        @Override
        public void onNoConditionAssembles() {
            mOuter.mloadCover.setVisibility(View.VISIBLE);
            mOuter.mloadCover.onRefreshFailed("暂无数据");
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.sumOfMoneyList = null;
            mOuter.money.clear();
            mOuter.sumofrealmoney.setText("实收总金额：00.00");
            mOuter.sumofmoney.setText("应收总金额：00.00");
            mOuter.sumOfMoneyAdapter.notifyDataSetChanged();
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }


        }

        @Override
        public void onResponseSuccess(SumOfMoney sumOfMoney) {
            if(mOuter == null){
                return;
            }
            mOuter.sumOfMoneyList = null;
            mOuter.money.clear();
            mOuter.sumOfMoneyList = sumOfMoney;
            mOuter.money.addAll(mOuter.sumOfMoneyList.getMoney());
            mOuter.sumofrealmoney.setText("实收总金额：" + mOuter.sumOfMoneyList.getReal_total_money());
            mOuter.sumofmoney.setText("应收总金额："+mOuter.sumOfMoneyList.getTotal_money());
            mOuter.sumOfMoneyAdapter.notifyDataSetChanged();
            mOuter.mloadCover.onRefreshSuccess();
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
        }

        @Override
        public void onNoMoreData() {
            if(mOuter == null){
                return;
            }
            mOuter.mloadCover.setVisibility(View.VISIBLE);
            mOuter.mloadCover.onRefreshFailed("暂无数据");
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
        }

        @Override
        public void onNoNetWork() {
            if(mOuter == null){
                return;
            }
            mOuter.mloadCover.onRefreshFailed();
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
        }

        @Override
        public void onResponseFailed() {
            if(mOuter == null){
                return;
            }
            mOuter.mloadCover.onRefreshFailed();
            if(mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
        }

    }


}
